export const url = 'https://api.yingyingtang.cn/api'
const SERVER_URL = "https://api.yingyingtang.cn/api"


// store.156.run
export default {
	serverUrl: SERVER_URL,
	code: {
		success: 2000,
		fail: 4000,
		invalidCredential: 10021,
		repeatPayment: 900,
		insufficientBalance: 901
	},
	request(method, url, data, successCallback, failCallback, completeCallback) {
		// 获取 token
		let token = uni.getStorageSync("token")
		// 对整体请求的统一封装
		uni.request({
			method: method,
			url: SERVER_URL + url,
			data: data,
			dataType: "json",
			header: {
				'authorization': token
			},
			success: (res) => {

				if (res.data.code == 401) {
					console.log("token 过期，需要登录")
					uni.removeStorageSync("token")
					uni.redirectTo({
						url: '/pages/splash-screen/splash-screen'
					})
					return
				}
				if (successCallback) {
					successCallback(res.data)
				}
			},
			fail: (res) => {
				if (res.statusCode == 403) {
					// token 过期，需要登录
					// uni.navigateTo({
					// 	url: '/pages/login/sign-in'
					// })
					this.loginFromWechat(this.loginSuccess, this.loginFailed, "")

				}
				console.log("Failed");
				if (failCallback) {
					failCallback(res.data)
				}
			},
			complete: () => {
				if (completeCallback) {
					completeCallback()
				}
			}
		});
	},
	data: {
		isLoginInProgress: false, // 登录操作 mutex lock
		pinUser: null
	},
	invokers: {},
	setData(key, value) {
		this.data[key] = value;
		this.invokers[key].setData({
			[key]: value
		})
	},
	getData(key, value) {
		return this.data[key]
	},
	bindData(key, value, invoker) {
		this.data[key] = value;
		this.invokers[key] = invoker
	},
	getToken() {
		return uni.getStorageSync("pin-token")
	},
	loginSuccessCallback: null,
	setLoginSuccessCallback(loginSuccessCallback) {
		this.loginSuccessCallback = loginSuccessCallback
	},

	//1.0获取oss预签名
	getUploadParams(type, successCallback, failCallback) {
		var param = {
			type
		}
		this.request('GET', `/assets/upload`, param,
			successData => {
				if (successData.code == this.code.success) {
					successCallback(successData.data)
				} else {
					failCallback(successData)
				}

			}, error => {
				failCallback(successData)
			})
	},
	//2.0上传服务器
	generateAsset(path, file_name, type, successCallback, failCallback) {
		var param = {
			path,
			file_name,
			type
		}
		this.request('POST', `/assets/generate`, param,
			successData => {
				if (successData.code == this.code.success) {
					successCallback(successData.data)
				} else {
					failCallback(successData)
				}

			}, error => {
				failCallback(successData)
			})
	},
	//微信登陆
	loginFromWechat(successCallback, failCallback, phoneCode) {
		if (this.data.isLoginInProgress) {
			console.log("登录操作正在进行，互斥锁阻止继续执行")
			return
		}

		this.data.isLoginInProgress = true
		let that = this
		uni.login({
			provider: 'wexin',
			success: (loginRes) => {
				let code = loginRes.code
				console.log('code：' + JSON.stringify(code));
				var param = {
					code
				}
				//先调用登陆接口
				that.request('POST', `/auth/login`, param,
					successData => {

						if (successData.code == that.code.success) {
							var uid = successData.data.id
							var phoneParam = {
								phone: phoneCode
							}
							//调用获取手机号登陆接口
							that.request('POST', `/auth/${uid}/phone`, phoneParam, success => {
								that.data.isLoginInProgress = false
								if (success.code == that.code.success) {
									// 保存到 storage
									uni.setStorageSync('token', success.data.token)
									uni.setStorageSync("phone", success.data.phone)
									uni.setStorageSync("uid", success.data.id)
									uni.setStorageSync("invite_code", success.data.invite_code)
									uni.setStorageSync("staff_id", success.data.staff_id)





									if (successCallback) {
										successCallback()
									}
									if (that.loginSuccessCallback) {
										that.loginSuccessCallback()
									}
									// 	that.getPinUserInfo(successData.data.token)
								} else {
									failCallback(success)
								}


							}, error => {

							})
						}

					}, error => {


					})
			},
			fail: (e) => {
				that.data.isLoginInProgress = false
				console.log("fail: " + JSON.stringify(e));
			}
		});
	},
	getPinUserInfo(token) {
		let that = this
		this.request('POST', 'istore/user/info', null,
			successData => {

				that.data.pinUser = successData.data
				uni.setStorageSync('pinUser', successData.data)
			},
			failData => {
				console.log(failData)
				uni.showToast({
					icon: 'none',
					title: '加载全局用户信息时出错'
				})
			}
		)
	},
	getFriendlyTimeText(dateTimeStamp) {
		var time = dateTimeStamp
		let targetDate = new Date(time)
		let result = "";
		let minute = 1000 * 60;
		let hour = minute * 60;
		let day = hour * 24;
		let halfamonth = day * 15;
		let month = day * 30;
		// let now = new Date().getTimezoneOffset();
		let now = new Date(new Date().getTime() + new Date().getTimezoneOffset() * 60000);
		console.log("零时区时间", now)
		let diffValue = now - targetDate.getTime();
		if (diffValue < 0) {
			return "刚刚";
		}
		let monthC = diffValue / month;
		let weekC = diffValue / (7 * day);
		let dayC = diffValue / day;
		let hourC = diffValue / hour;
		let minC = diffValue / minute;
		if (weekC >= 1) {
			// result = targetDate.getFullYear() + '-' + targetDate.getMonth() + '-' + targetDate.getDate() + ' ' + targetDate.getHours() +
			// 	':' + targetDate.getMinutes() + ':' + targetDate.getSeconds()
			result = "" + parseInt(weekC) + "周前";
		} else if (dayC >= 1) {
			result = "" + parseInt(dayC) + "天前";
		} else if (hourC >= 1) {
			result = "" + parseInt(hourC) + "小时前";
		} else if (minC >= 1) {
			result = "" + parseInt(minC) + "分钟前";
		} else
			result = "刚刚";
		return result;
	},
	getUUID() {
		return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
			var r = (Math.random() * 16) | 0,
				v = c == 'x' ? r : (r & 0x3) | 0x8;
			return v.toString(16);
		})

	},

	getTemplateNameById(templateId) {

		switch (templateId) {
			case "STT_Glnn5KD9VZj":
				return "四方格";
				break;
			case "STT_nd7l511D1z0":
				return "轮播图";
				break;
			case "STT_ODKKOVRGqOM":
				return "横向瀑布流";
				break;
			case "STT_NDJJobQNYYP ":
				return "纵向瀑布流";
				break;
			default :
				return "";
				break;
		
		}


	}
}